// 封装购物车模块
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './userStore'
import { insterCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() =>  userStore.userInfo.token)
    // 1. 购物车中商品列表
    const cartList = ref([])
    // 2. 添加购物车 - addcart
    const addCart = async (goods) => {
        const { skuId, count } = goods
        if(isLogin.value){
            await insterCartAPI({ skuId, count })
            updateNewList()
        } else {
            // 添加购物车操作
            // 已添加过count +1
            // 没有添加过 - 直接push
            // 通过匹配传递过来的商品对象的skuid能不能在商品列表中找到
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            if(item){
                // 找到了
                item.count++
            } else {
                // 没找到 添加商品
                cartList.value.push(goods)
            }
        }
        
    }
    
    // 删除购物车
    const delCart = async (skuId) => {
        if(isLogin.value){
            await delCartAPI([skuId])
            updateNewList()
        } else{
            const newList = cartList.value.filter(item => skuId !== item.skuId)
            cartList.value = newList
        } 
    }

    // 获取购物车列表
    const updateNewList = async () => {
        const res = await findNewCartListAPI()
        cartList.value = res.result
    }

    // 退出登录清除购物车数据
    const clearCart = () => {
        cartList.value = []
    }
    
    // 单选功能
    const singleCheck = (skuId, selected) =>{
        const item = cartList.value.find(item => item.skuId === skuId)
        item.selected = selected
    }

    // 是否全选
    const isAll = computed(() =>  cartList.value.every(item => item.selected))
    
    // 全选功能
    const allCheck = (selsected) => {
        cartList.value.forEach(item => item.selected = selsected)
    }


    // 购物车总数量
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    // 购物车总价格
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))

    // 已选商品的数量
    const selsectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
    // 已选商品的价格
    const selsectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))
    
    return {
        cartList,
        allCount,
        allPrice,
        isAll,
        selsectedCount,
        selsectedPrice,
        clearCart,
        addCart,
        delCart,
        singleCheck,
        allCheck,
        updateNewList
    }
},{
    persist: true
})